package com.xuexiang.xui_lib.component.button;

import ohos.agp.components.AttrSet;
import ohos.app.Context;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;

public class CountDownButton extends SuperButton implements Runnable {

    private final EventHandler HANDLER = new EventHandler(EventRunner.getMainEventRunner());

    private int count = 0;
    private boolean isStop;
    private boolean isDowning;
    private int realCount = -1;
    private static final Object lock = new Object();
    private CountDownListener listener;

    public interface CountDownListener {
        void downCount(CountDownButton button, int count);

        void finish(CountDownButton button);
    }

    public CountDownButton(Context context) {
        this(context, null);
    }

    public CountDownButton(Context context, AttrSet attrSet) {
        this(context, attrSet, null);
    }

    public CountDownButton(Context context, AttrSet attrSet, String styleName) {
        super(context, attrSet, styleName);
    }

    public void start() {
        synchronized (lock) {
            if (isDowning || listener == null) {
                return;
            }
            setEnabled(false);
            setClickable(false);
            onStart();
        }

    }

    public void stop() {
        synchronized (lock) {
            isStop = true;
        }
    }

    public void reset() {
        count = realCount;
        isStop = false;
        isDowning = false;
        setEnabled(true);
        setClickable(true);
        if (HANDLER != null) {
            HANDLER.removeTask(this);
        }
    }

    public void setCount(int count) {
        if (count <= 0) return;
        this.count = count;
        realCount = count;
    }

    public void setCountDownListener(CountDownListener listener) {
        this.listener = listener;
    }

    private void onStart() {
        if (HANDLER != null) {
            isStop = false;
            HANDLER.postTask(this);
        }
    }

    @Override
    public void run() {
        if (isStop) {
            return;
        }
        count--;
        if (listener != null) {
            listener.downCount(this, count);
        }
        if (count == 0) {
            if (listener != null) {
                listener.finish(this);
            }
            reset();
        } else {
            if (HANDLER != null) {
                HANDLER.postTask(this, 1000);
            }
        }
    }

    public static class CountDownButtonHelp {

        public static void applyCountDownButton(CountDownButton countDownButton, int count, CountDownListener listener) {
            countDownButton.setCountDownListener(listener);
            countDownButton.setCount(count);
            countDownButton.setClickedListener(component -> countDownButton.start());
        }

    }

}
